countryData <- function(x,countryCoolumn="ISO3",...){
  UseMethod("countryData")
}

countryData.default <- function(x,countryColumn,...){
  ## read the data:
  data = read.csv(x,...)

  return(countryData(data),countryColumn)
}

countryData.data.frame <- function(x,countryColumn){

  ## check the codes:
  if(!countryColumn %in% names(x)){
    stop("No column ",countryColumn," in file")
  }

  attr(x,"countryColumn") = countryColumn
  class(x)=c("countryData","data.frame")
  return(x)
  
}

print.countryData <- function(x,...){
  cat("Country data\n\n")
  NextMethod()
  col=attr(x,"countryColumn")
  cat("\n - Country Code in column ",col,"\n",sep="")
  return(invisible(0))
}

plot.countryData <- function(x,data,map=getMap(),code="ISO3",
                             palette="auto",...){
  dataNames = x[,attr(x,'countryColumn')]
  mapNames = map@data[,code]

  ## are all our data on the map?
  dataIndices = match(dataNames,mapNames)
  missingData = is.na(dataIndices)
  if(any(missingData)){
    miss = dataNames[missingData]
    if(nchar(miss)>80){
      miss=paste(substr(miss,1,80),"... (",sum(missingData)," in total)",sep="")
    }
    warning("Some rows of your data did not match the map: ",paste(miss,collapse=","),sep="")
  }

  ## is all of our map covered by the data?
  mapIndices = match(mapNames,dataNames)
  missingMap = is.na(mapIndices)
  if(any(missingMap)){
    miss = paste(mapNames[missingMap],collapse=",")
    if(nchar(miss)>80){
      miss=paste(substr(miss,1,80),"... (",sum(missingMap)," in total)",sep="")
    }
    warning("Some map regions are not covered by your data: ",paste(miss,collapse=","),sep="")
  }

  ex = structure(as.list(match.call()[-1]),class="uneval")
  dataValues = eval(parse(text=ex$data),env=x,enclos=NULL)
  mapPart = map[!is.na(mapIndices),]
  mapData = dataValues[mapIndices[!is.na(mapIndices)]]

  colours = computeColours(mapData,palette)
  
  plot(mapPart,col=colours,...)

  return(invisible(0))

}
